//
//  SEChatViewController+Data.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/27.
//

import UIKit

// MARK: - 数据请求处理

extension SEChatViewController {
    @objc func loadData() {
        refreshIndicator.animating = true
        viewModel.getDataOfOnlineInquiry()
    }
    
    @objc func generateMessageId() {
        viewModel.generateMessageId(messageType)
    }
    
    @objc func pullToLoadMore() {
        isEndRefreshing = false
        isReloading = true
        
        viewModel.getMoreListOfChatRecord()
    }
    
    func changeOnlineInquiryStatus(_ status: SEInquiryChangeStatus) {
        viewModel.changeOnlineInquiryStatus(status)
    }

    func getVideoAccount() {
        viewModel.getVideoAccount()
    }
}

// MARK: - 消息处理

extension SEChatViewController {
    func checkSendTextEnable() {
        guard let textView = self.chatActionBarView.inputTextView else { return }
        guard textView.text.count < 1000 else {
            SEHUD.show(message: "超出字数限制", position: .top)
            return
        }
        guard textView.text.trimmingCharacters(in: .whitespaces).count > 0 else {
            SEHUD.show(message: "不能发送空白消息", position: .top)
            return
        }
        
        messageType = .text
        waitSendMsgContent = textView.text
        generateMessageId()
        chatActionBarView.inputTextView.text = nil // 发送完后置空
        textViewDidChange(chatActionBarView.inputTextView)
    }
    
    /// 发送文字消息
    func sendChatTextMessage() {
        dispatch_async_safely_main_queue {
            let model = self.viewModel.chatRecord(self.waitSendMsgContent, messageType: .text)
            let insertIndexPaths = self.viewModel.insertChatRecordOfMessage(model)
            self.msgTableView.insertRowsAtBottom(insertIndexPaths)
            
            SEIMManager.shared.sendMessage(model)
            
            self.waitSendMsgContent = "" // 发送完后置空
        }
    }

    /// 发送视频通话消息
    func sendVideoCallMessage() {
        dispatch_async_safely_main_queue {
            let model = self.viewModel.chatRecord("0", messageType: .videoCall)
            let insertIndexPaths = self.viewModel.insertChatRecordOfMessage(model)
            self.msgTableView.insertRowsAtBottom(insertIndexPaths)

            SEIMManager.shared.sendMessage(model)
        }
    }
    
    /// 发送聊天图片消息
    func sendChatImageMessage(_ image: UIImage?) {
        guard let image = image else { return }
        
        isImageUploading = true
        
        uploadVM.uploadImage(bucket: "H", type: "H-1", image: image, size: image.imageSize(), isIm: 1)
        
        uploadVM.updateData = { [weak self] status in
            self?.isImageUploading = false
            guard let self = self else { return }
            switch status {
            case .success:
                dispatch_async_safely_main_queue {
                    let model = self.viewModel.chatRecord(self.uploadVM.fileModel?.shareThumbnailUrl, url: self.uploadVM.fileModel?.shareUrl, messageType: .image)
                    let insertIndexPaths = self.viewModel.insertChatRecordOfMessage(model)
                    self.msgTableView.insertRowsAtBottom(insertIndexPaths)
                    
                    SEIMManager.shared.sendMessage(model)
                }
            default:
                break
            }
        }
    }
    
    /// 发送语音
    func sendChatVoice() {

    }
    
    func sendFileAuthorizeMessage() {
        dispatch_async_safely_main_queue {
            let status = SEPatientFileAuthorizedStatus.unauthorized
            let model = self.viewModel.chatRecord(status.rawValue, messageType: .fileAuthorize)
            let insertIndexPaths = self.viewModel.insertChatRecordOfMessage(model)
            self.msgTableView.insertRowsAtBottom(insertIndexPaths)
            
            SEIMManager.shared.sendMessage(model)
        }
    }
    
    func sendEndInquiryMessage() {
        dispatch_async_safely_main_queue {
            let status = SEInquiryChangeStatus.waitEnd
            let model = self.viewModel.chatRecord(status.rawValue, messageType: .endInquiry)
            let insertIndexPaths = self.viewModel.insertChatRecordOfMessage(model)
            self.msgTableView.insertRowsAtBottom(insertIndexPaths)
            
            SEIMManager.shared.sendMessage(model)
        }
    }
}

extension SEChatViewController {
    func handleIMMessage() {
        SEIMManager.shared.sendMessageHandler = { model in
            SELog("+++++++++++ send message hander: \(model)")
            
            if let cacheKey = model.msgId, SEImageFilesManager.image(forKey: cacheKey) != nil {
                SEImageFilesManager.removeImage(forKey: cacheKey)
            }
            
            if let indexPath = self.viewModel.changeMessageSendStatus(model) {
                self.msgTableView.reloadRows(at: [indexPath], with: .none)
            }
        }
        
        SEIMManager.shared.receiveMessageHandler = { model in
            SELog("+++++++++++ receive message hander: \(model)")
            switch model.cmd {
            case SEChatCMD.message.rawValue:
                if model.msgType == SEChatMessageType.fileAuthorize.rawValue {
                    let status = SEPatientFileAuthorizedStatus(rawValue: model.content ?? "1")
                    guard status != .unauthorized else { return }
                    
                    SEHUD.show(message: status?.message)
                    
                    self.loadData()
                    
                    return
                }
                
                guard self.viewModel.makeSureChatRecordIsUnique(model: model) else { return }
                
                let insertIndexPaths = self.viewModel.insertChatRecordOfMessage(model)
                self.msgTableView.insertRowsAtBottom(insertIndexPaths)
            case SEChatCMD.inquiryStatusChanged.rawValue:
                switch model.status {
                case .confirmEnd, .rejectEnd:
                    self.viewModel.updateInquiryDealStatus(model.status)
                    self.loadData()
                default: break
                }
            case SEChatCMD.prescriptionStatusChanged.rawValue:
                guard model.prescription?.status == .passed ||
                        model.prescription?.status == .noDrug ||
                        model.prescription?.status == .paid else { return }
                
                guard self.viewModel.makeSureChatRecordIsUnique(model: model) else { return }
                
                let insertIndexPaths = self.viewModel.insertChatRecordOfMessage(model)
                self.msgTableView.insertRowsAtBottom(insertIndexPaths)
            default:
                break
            }

        }
    }
}
